<?php
uses('model');

class usersModel extends Model {

    function __construct() {
        parent::__construct();
        $this->dbconnect();
        //if ($_SESSION['admin']) $this->db->debug();
    }

    function register($v) {
        /*
        1.成功
        2.已存在
        4.失败
        256.Email已存在
        */
        $this->dbconnect();

        $data['code']['register'] = 1;
        $v['created'] = time();
        unset($v['password_r']);

        if (!$v['email']) {
            $data['code']['register'] = 64;
            return $data;
        }

        if ($this->db->count($this->table['users'], 'username='.$this->db->qstr($v['username'])) > 0) {
            $data['code']['register'] = 2;
        } else if ($this->db->count($this->table['users'], 'email='.$this->db->qstr($v['email'])) > 0) {
            $data['code']['register'] = 256;
        } else if (!$this->db->insert($this->table['users'], $v)) {
            $data['code']['register'] = 4;
        } else {
            //新用户 Id
            $data['id'] = $this->db->insertid();

            /*
            //折扣代码生成
            $vc =& getController('voucher');
            $vv['prend'] = 'NEW';
            $vv['price'] = 10;
            $vv['minprice'] = 1;
            $vv['expiredtime']  = time()+3600*24*30;
            $vv['code'] = $vc->addVoucher($vv);

            //$needprice = $price*$this->cfg['voucher'];

            //成功,发邮件
            $fields['sendto']   = $v['nickname'];
            $fields['mailto']   = $v['email'];
            $fields['subject']  = $v['nickname'].', 欢迎加入乐铺';
            $fields['body']     = "{$v['nickname']}：\r\n\r\n".
            $fields['body']    .= "恭喜您已经成为了乐铺的会员。以下是乐铺专为您送出的 {$vv['price']} 元折扣代码，可在乐铺下订单页面中使用，无任何限制哦，请妥善保管。\r\n\r\n";
            $fields['body']    .= "\r\n      代码:  {$vv['code']}    30 天内有效哦\r\n\r\n\r\n";
            $fields['body']    .= "使用过程中有任何问题，欢迎及时联系我们，很乐意能为您提供服务。";
            $fields['created']  = time();

            $this->db->Insert($this->table['mail'], $fields);
            unset($fields);
             */
        }

        return $data;
    }

    function login($v) {
        $this->dbconnect();
        /*
        4.登录成功
        5.用户名密码不匹配
        */
        $where[] = '(username='. $this->db->qstr($v['username']) .' AND md5(password)='. $this->db->qstr($v['password']) .')';
        $where[] = '(email='. $this->db->qstr($v['username']) .' AND md5(password)='. $this->db->qstr($v['password']) .')';
        $where = join(' OR ', $where) . ' ORDER by id ASC';

        if ($rs = $this->db->GetRow($this->table['users'], '*', $where)) {
            $data['rs'] = $rs;
            $data['code']['login'] = 4;

            //重新统计购物车中数量
            $tmp = $this->db->GetRow($this->table['shopcar'], 'SUM(amount) as a, SUM(price*amount) as b', "sessionid='{$v['sessionid']}'");
            $data['caramount'] = $tmp['a'];
            $data['carprice'] = $tmp['b'];

            //删除购物车中的无主物品 一星期没有更新的
            $this->db->Delete($this->table['shopcar'], "uid=0 AND updated<" . (time()-3600*24*7));

            //更新最后登录时间
            $this->db->Update($this->table['users'], array('lastlogin'=>time()), "id={$rs['id']}");

        } else {
            $data['code']['login'] = 8;
        }

        return $data;
    }

    function forgotpwd($v) {
        $this->dbconnect();
        /*
        4.用户名密码不匹配
        8.发送成功
        16.发送失败
        */
        if ($rs = $this->db->GetRow($this->table['users'], '*', 'username='. $this->db->qstr($v['username']) .' AND email='. $this->db->qstr($v['email']) )) {
            //$data['rs'] =& $rs;
            //echo 'Todo:发送密码找回邮件到'.$rs['email'].' For 用户'.$rs['username'];

            /*
            uses('mail');
            $m = new mail;

            $m->AddAddress($rs['email'], $rs['username']);
            $m->Subject =   '乐铺密码找回通知';
            $m->Body    =   "亲爱的{$rs['username']}：\r\n\r\n".
            $m->Body    .=  "您曾申请在乐铺取回密码，您的密码是{$rs['password']}，密码区分大小写，请妥善保管。\r\n\r\n";
            $m->Body    .=  "有任何问题请及时联系我们。\r\n\r\n";
            $m->Body    .=  "          乐铺 敬上\r\n          LooPo.cn";

            if (@$m->Send()) xxx
            */

            //Rand pass
            $newpass = strtolower(substr(md5(uniqid(rand(),true)), rand(0,26), 8));

            $fields['sendto']   = $rs['username'];
            $fields['mailto']   = $rs['email'];
            $fields['subject']  = '乐铺密码找回通知';
            $fields['body']     =   "亲爱的{$rs['username']}：\r\n\r\n".
            $fields['body']    .=  "您申请在乐铺取回密码。我们为您重置了密码，您的新密码是{$newpass}，密码全部为小写，请妥善保管。\r\n\r\n用新密码登录后您可以在“我的乐铺”功能中修改您的密码。\r\n\r\n";
            $fields['body']    .=  "有任何问题请及时联系我们。";
            $fields['created']  = time();

            if ($this->db->Insert($this->table['mail'], $fields)) {
                $data['code']['forgotpwd'] = 8;
                $this->db->Update($this->table['users'], array('password'=>$newpass), 'username='. $this->db->qstr($v['username']));
            } else {
                $data['code']['forgotpwd'] = 16;
            }

        } else {
            $data['code']['forgotpwd'] = 4;
        }

        return $data;
    }

    function usersList($v) {
        $this->dbconnect();

        if ($v['sort']) {
            $cols = $this->db->_db->MetaColumnNames($this->table['users']);
            if (!in_array($v['sort'],$cols)) $v['sort'] = 'id';
        } else {
            $v['sort'] = 'id';
        }

        if ($v['ids'])
            $where = "id IN({$v['ids']})";
        else
            $where = $v['search'] ? $this->makelikequery($v['search'], array('username','email','truename'), $this->db) : '1';

        if ($v['pagesize']) {
            //$rs = $this->db->Limit($this->table['users'], '*', "$where ORDER BY ".$v['sort']." {$v['sortorder']}", intval($v['pagestart']), $v['pagesize']);
            $data['list'] = $this->db->GetPage(array($this->table['users'], '*', "$where ORDER BY ".$v['sort']." {$v['sortorder']}"), $data['page'], $v['pagesize']);
        } else
            $data['list'] = $this->db->GetAll($this->table['users'], '*', "$where ORDER BY ".$v['sort']." {$v['sortorder']}");

        return $data;
    }

    function usersEdit($v) {
        $this->dbconnect();

        /*
        1.update成功
        2.失败
        */
        if ($v['remove']) {
            $data['remove'] = true;
            $this->db->Delete($this->table['users'], "id={$v['id']}");
        } else {
            $data['code']['usersEdit'] = $this->db->update($this->table['users'], $v['fields'], "id={$v['id']}") ? 1 : 2;
        }
        return $data;
    }

    //收货地址列表
    function userAddressList($v) {
        $this->dbconnect();

        return $this->db->GetAll($this->table['address'], '*', "uid={$v['uid']}");
    }

    function userAddressUpdate($v) {
        $this->dbconnect();

        $where = "uid={$v['uid']} AND id={$v['id']}";

        if ($v['remove']) {
            /*
            1.成功
            2.失败
            4.主地址不能删除
            */
            if($this->db->GetOne($this->table['address'], 'paddr', $where." AND paddr=1") == 1)
                $data['code']['userAddressUpdate'] = 4;
            else
                $data['code']['userAddressUpdate'] = $this->db->Delete($this->table['address'], $where);
        } else {
            if ($v['uid'])      $fields['uid']      = $v['uid'];
            if ($v['address'])  $fields['address']  = $v['address'];
            if ($v['tel'])      $fields['tel']      = $v['tel'];
            if ($v['linkman'])  $fields['linkman']  = $v['linkman'];
            if ($v['zipcode'])  $fields['zipcode']  = $v['zipcode'];
            if ($v['paddr'])    $fields['paddr']    = $v['paddr'];

            /*
            1.成功
            2.失败
            8.资料不完整
            */

            if ($v['id']) {
                $this->db->Update($this->table['address'], array('paddr'=>0), "uid={$v['uid']}");
                $data['code']['userAddressUpdate'] = $this->db->Update($this->table['address'], $fields, $where) ? 1 : 2;
            } else
                $data['code']['userAddressUpdate'] = $this->db->Insert($this->table['address'], $fields) ? 1 : 2;
        }

        return $data;
    }

    function userWishList($v) {
        $this->dbconnect();

        if ($v['pagesize']) {
            $data['list'] = $this->db->GetPage(array("{$this->table['wishlist']} a LEFT JOIN {$this->table['items']} b ON a.iid = b.id", 'b.id, b.name, b.price1', "a.uid={$v['uid']} ORDER BY a.". ($v['sort'] ? $v['sort'] : 'id') ." ".  ($v['sortorder'] ? $v['sortorder'] : 'DESC')), $data['page'], $v['pagesize']);
        } else {
            $data['list'] = $this->db->GetAll("{$this->table['wishlist']} a LEFT JOIN {$this->table['items']} b ON a.iid = b.id", 'b.id, b.name, b.price1', "a.uid={$v['uid']} ORDER BY a.". ($v['sort'] ? $v['sort'] : 'id') ." ".  ($v['sortorder'] ? $v['sortorder'] : 'DESC') );
        }
        return $data;
        /*
        if ($ids = $this->db->GetCol($this->table['wishlist'], 'iid', "uid={$v['uid']} ORDER BY ". ($v['sort'] ? $v['sort'] : 'id') ." ".  ($v['sortorder'] ? $v['sortorder'] : 'DESC'))) {
            $ids = join(',', $ids);
            return $this->db->GetAll($this->table['items'], '*', "id IN($ids)");
        } else {
            return false;
        }
        */
    }

    function userWishListDel($v) {
        $this->dbconnect();
        $data['code']['userWishListDel'] = $this->db->Delete($this->table['wishlist'], "uid={$v['uid']} AND iid={$v['iid']}") ? 1 : 2;
        return $data;
    }

	function userWishListAddress($v) {
		$this->dbconnect();
        $data['code']['userWishListAddress'] = $this->db->Update($this->table['users'], $v['fields'], "id={$v['uid']}") ? 1 : 2;

		return $data;
	}

    function byName($v) {
        $this->dbconnect();
        $data = $this->db->GetRow($this->table['users'], '*', "username=".$this->db->qstr($v));

        return $data;
    }

    function byId($v) {
        $this->dbconnect();
        $data = $this->db->GetRow($this->table['users'], '*', "id=".intval($v));

        return $data;
    }

    function byEmail($v) {
        $this->dbconnect();
        $data = $this->db->GetAll($this->table['users'], '*', "email=".$this->db->qstr($v));

        return $data;
    }

    function getOpenIDById($v) {
        $this->dbconnect();
        $data = $this->db->GetCol($this->table['openid'], 'url', "uid=".intval($v));

        return $data;
    }

    function getIdByOpenID($v) {
        $this->dbconnect();
        $data = $this->db->GetOne($this->table['openid'], 'uid', "url=".$this->db->qstr($v));

        return $data;
    }

    function addOpenID($v) {
        $this->dbconnect();

        return $this->db->Insert($this->table['openid'], $v);
    }

    function delOpenID($v) {
        $this->dbconnect();

        if ($v['url']) $where[] = "url=".$this->db->qstr($v['url']);
        if ($v['uid']) $where[] = "uid=".intval($v['uid']);

        if ($where) {
            $where = join(' AND ', $where);
            $result = $this->db->delete($this->table['openid'], $where);
        }

        return $result ? true : false;
    }
}
?>
